package com.bright.ghj.overt.web.controller;

import com.bright.ghj.common.pojo.vo.PageVO;
import com.bright.ghj.common.pojo.bo.RestResult;
import com.bright.ghj.overt.pojo.vo.*;
import com.bright.ghj.overt.util.SecurityUtil;
import com.bright.ghj.common.util.StringUtil;
import com.bright.ghj.overt.constant.PublicConstant;
import com.bright.ghj.overt.pojo.command.OpenReportOperateIdsCommand;
import com.bright.ghj.overt.pojo.dto.TableDataDTO;
import com.bright.ghj.overt.pojo.dto.UserDTO;
import com.bright.ghj.overt.pojo.query.OpenReportRecordQuery;
import com.bright.ghj.overt.pojo.query.TableDataIdQuery;
import com.bright.ghj.overt.pojo.query.TableDataQuery;
import com.bright.ghj.overt.service.BaseDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author hxj
 * @Date 2023/12/21 10:45
 * @Description 报表数据处理
 */
@RequestMapping("/baseData")
@RestController
@RequiredArgsConstructor
@Api(tags = "基础数据接口")
public class BaseDataController {

    private final BaseDataService baseDataService;

    /**
     * 获取当前表的表头列表
     * @return 表头列表
     */
    @ApiOperation(value = "获取基础数据表头")
    @GetMapping("/tableHeader/list")
    public RestResult listTableHeaders(String tableName) {
        List<TableHeaderVO> tableHeaders = baseDataService.listTableHeaders(tableName);
        return RestResult.success(tableHeaders);
    }

    /**
     * 获取当前表的表头列表
     * @return 表头列表
     */
    @ApiOperation(value = "获取基础数据表头 按open表id")
    @GetMapping("/tableHeader/list/id")
    public RestResult listTableHeadersById(Integer id) {
        Map<String, Object> result = new HashMap<>();
        TableDataIdQuery tableDataIdQuery = new TableDataIdQuery();
        tableDataIdQuery.setId(id);
        TableInfoVO tableInfo = baseDataService.getTableInfo(tableDataIdQuery);
        // 主表表头
        String tableName = tableInfo.getTableName();
        result.put("headers", baseDataService.listTableHeaders(tableName));

        // 子表表头
        Map<String, List<TableHeaderVO>> subTableHeaders = new HashMap<>();
        for (String subTableName : tableInfo.getSubTableNames()) {
            subTableHeaders.put(subTableName, baseDataService.listTableHeaders(subTableName));
        }
        result.put("subHeaders", subTableHeaders);

        return RestResult.success(result);
    }

    @ApiOperation(value = "分页获取子表数据")
    @PostMapping("/tableData/page")
    public RestResult pageTableData(@RequestBody @Valid TableDataQuery tableDataQuery) {
        PageVO pageTableData = baseDataService.pageTableData(tableDataQuery);
        return RestResult.success(pageTableData);
    }

    @ApiOperation(value = "分页获取子表数据 按openReportRecord表的id")
    @PostMapping("/tableData/page/id")
    public RestResult pageTableDataById(@RequestBody @Valid TableDataIdQuery tableDataIdQuery) {
        PageVO pageTableData = baseDataService.pageTableData(tableDataIdQuery);
        return RestResult.success(pageTableData);
    }

    @ApiOperation(value = "不分页获取子表数据 按openReportRecord表的id")
    @PostMapping("/tableData/list/id")
    public RestResult listTableDataById(@RequestBody @Valid TableDataIdQuery tableDataIdQuery) {
        PageVO pageTableData = baseDataService.listTableData(tableDataIdQuery);
        return RestResult.success(pageTableData);
    }

    @PreAuthorize("hasAnyAuthority('cwgkEdit','dwgkEdit','swgkEdit')")
    @ApiOperation(value = "保存主表子表数据")
    @PostMapping("/tableData/save")
    public RestResult saveTableData(@RequestBody @Valid TableDataDTO tableDataDTO) {
        SaveResultVO saveResultVO;

        // 兼容两种传值方式 可以只传openReportRecord的id 若不传id 则必传年月账套号表名
        if (tableDataDTO.getId() == null || tableDataDTO.getId() == 0) {
            StringBuilder errorInfo = new StringBuilder();
            if (tableDataDTO.getYears() == null || tableDataDTO.getYears() == 0) {
                errorInfo.append("年份不能为空！");
            }
            if (StringUtil.isEmpty(tableDataDTO.getZtId())) {
                errorInfo.append("账套不能为空！");
            }
            if (StringUtil.isEmpty(tableDataDTO.getTableName())) {
                errorInfo.append("表名不能为空！");
            }

            if (StringUtil.isNotEmpty(errorInfo)) {
                return RestResult.fail(errorInfo.toString());
            }
        }

        try {
            saveResultVO = baseDataService.saveTableData(tableDataDTO);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return RestResult.fail("保存失败：" + throwable.getMessage());
        }
        return RestResult.success(saveResultVO);
    }

    /**
     * 获取当前表是否已审核 已发布
     * @param tableDataIdQuery 查询
     * @return 审核状态 发布状态 是否可编辑 footer脚注
     */
    @ApiOperation(value = "获取当前表信息")
    @PostMapping("/tableData/info")
    public RestResult getTableInfo(@RequestBody @Valid TableDataIdQuery tableDataIdQuery) {
        TableInfoVO tableInfoVO = baseDataService.getTableInfo(tableDataIdQuery);

        // 判断当前用户是否有权限编辑
//        String userName = getUserName();
//        tableInfoVO.setUserAbleEdit(navigateService.getUserAbleEdit(userName));
        // 临时代码
//        tableInfoVO.setPrtBtns(Arrays.asList(new ButtonVO("prt", "打印", "/nccw_rep/run?__report=reports/Rep999.rptdesign&__format=PDF&zth=040801001000&years=2024年"),
//                new ButtonVO("prtBatch", "批量打印", "/nccw_rep/run?__report=reports/plus.rptdesign&__format=PDF&zth=040801001000&years=2024&months=11")));
        tableInfoVO.setPrtBtns(baseDataService.getPrtBtns(tableDataIdQuery));
        return RestResult.success(tableInfoVO);
    }

    /**
     * 查询openReportRecord表-录入
     * @param openReportRecordQuery 查询
     * @return
     */
    @PreAuthorize("hasAnyAuthority('cwgkEdit','dwgkEdit','swgkEdit')")
    @ApiOperation(value = "获取公开主表信息-录入")
    @PostMapping("/openReportRecord/page")
    public RestResult pageOpenReportRecord(@RequestBody @Valid OpenReportRecordQuery openReportRecordQuery) {
        setUserDistNoZtId(openReportRecordQuery);
        PageVO<OpenReportRecordVO> pageVO = baseDataService.listOpenReportRecordByPage(openReportRecordQuery, PublicConstant.LIST_TYPE_EDIT);
        return RestResult.success(pageVO);
    }

    private void setUserDistNoZtId(OpenReportRecordQuery openReportRecordQuery) {
        UserDTO loginUser = SecurityUtil.getLoginUser();
        openReportRecordQuery.setUserDistNos(loginUser.getDistNoList());
        openReportRecordQuery.setUserZtIds(loginUser.getZtIdList());
    }

    /**
     * 查询openReportRecord表-审核
     * @param openReportRecordQuery 查询
     * @return
     */
    @PreAuthorize("hasAnyAuthority('cwgkAudit','dwgkAudit','swgkAudit') && hasAnyAuthority('isPermitAdmin')")
    @ApiOperation(value = "获取公开主表信息-审核")
    @PostMapping("/openReportRecord/audit/page")
    public RestResult pageOpenReportRecordAudit(@RequestBody @Valid OpenReportRecordQuery openReportRecordQuery) {
        setUserDistNoZtId(openReportRecordQuery);
        PageVO<OpenReportRecordVO> pageVO = baseDataService.listOpenReportRecordByPage(openReportRecordQuery, PublicConstant.LIST_TYPE_AUDIT);
        return RestResult.success(pageVO);
    }

    /**
     * 查询openReportRecord表-发布
     * @param openReportRecordQuery 查询
     * @return
     */
    @PreAuthorize("hasAnyAuthority('cwgkPublish','dwgkPublish','swgkPublish') && hasAnyAuthority('isPermitAdmin')")
    @ApiOperation(value = "获取公开主表信息-发布")
    @PostMapping("/openReportRecord/publish/page")
    public RestResult pageOpenReportRecordPublish(@RequestBody @Valid OpenReportRecordQuery openReportRecordQuery) {
        setUserDistNoZtId(openReportRecordQuery);
        PageVO<OpenReportRecordVO> pageVO = baseDataService.listOpenReportRecordByPage(openReportRecordQuery, PublicConstant.LIST_TYPE_PUBLISH);
        return RestResult.success(pageVO);
    }

    @PreAuthorize("hasAnyAuthority('cwgkEdit','dwgkEdit','swgkEdit')")
    @ApiOperation(value = "删除open表数据")
    @PostMapping("/openReportRecord/delete")
    public RestResult deleteOpenReportRecord(@RequestBody @Valid OpenReportOperateIdsCommand idsCommand) {
        SaveResultVO saveResultVO;

        if (idsCommand.getIds() == null || idsCommand.getIds().length == 0) {
            return RestResult.fail("未传递删除id！");
        }

        try {
            saveResultVO = baseDataService.deleteOpenReportRecordByIds(idsCommand.getIds());
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return RestResult.fail("删除失败：" + throwable.getMessage());
        }
        return RestResult.success(saveResultVO);
    }


}
